package com.igoal.web.security;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;

import com.igoal.entity.User;
import com.igoal.service.UserManagerExt;

public class CustomAuthenticationProcessingFilter extends AuthenticationProcessingFilter {

	private UserManagerExt userManagerExt;

	@Autowired
	public void setUserManagerExt(UserManagerExt userManagerExt) {
		this.userManagerExt = userManagerExt;
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request)
			throws AuthenticationException {
		final String REGISTER_FLAG = "register";
		String registerParam = request.getParameter(REGISTER_FLAG);
		String username = obtainUsername(request);

		if (REGISTER_FLAG.equals(registerParam)) {
			setDefaultTargetUrl("/welcome.html");
		} else if (userManagerExt.isDisable(username)) {
			setAuthenticationFailureUrl("/accountDisable.html?username=" + username);
		} else {
			setDefaultTargetUrl("/dashboard.html");
		}
		return super.attemptAuthentication(request);
	}

	@Override
	protected void onSuccessfulAuthentication(HttpServletRequest request,
			HttpServletResponse response, Authentication authResult) throws IOException {
		LoginStatus.login(((User) authResult.getPrincipal()).getUsername());
		super.onSuccessfulAuthentication(request, response, authResult);
	}
}
